package com.qianclass.talklive.app.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qianclass.talklive.R;
import com.qianclass.talklive.app.adapter.CourseAdapter;
import com.qianclass.talklive.app.adapter.ExpiredCourseAdapter;
import com.qianclass.talklive.app.bean.ExpiredRoomsBean;
import com.qianclass.talklive.app.bean.RoomsBean;
import com.qianclass.talklive.app.enter.IUserEnterPresenterImpl;
import com.qianclass.talklive.app.enter.IUserPlayRecordPresenterImpl;
import com.qianclass.talklive.app.utils.Constant;
import com.qianclass.talklive.app.utils.FileLogUtils;
import com.qianclass.talklive.app.utils.Info;
import com.qianclass.talklive.app.utils.LogUtil;
import com.qianclass.talklive.app.utils.ThreadUtils;
import com.qianclass.talklive.app.utils.ToastUtils;
import com.qianclass.talklive.app.utils.VerificationKeyUtils;
import com.qianclass.talklive.app.view.IBaseView;
import com.qianclass.talklive.app.view.LoadMoreListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CourseInfoActivity extends BaseActivity  implements IBaseView {


    private static final String TAG                     = "CourseInfoActivity";
    private static final int GETCOURSESUC               = 0;
    private static final int GTEXPIREDCOURSESUC         = 1;
    private static final int GETCOURSEFAIL               = 2;
    private static final int GTEXPIREDCOURSEFAL         = 3;
    private String mType   = "";
    private String mStatus = "";
    private int    mT, mS;
    private final static String USER_PWD = "userpwd";

    private String[] mCourseType = {"全部", "大班课", "小班课", "1对1"};
    private String[] mCourseStatus = {"未完成", "已完成"};

    ArrayList<RoomsBean>        mCourseList;
    ArrayList<ExpiredRoomsBean> mExpiredCourseList;

    String                   mToken;
    String                   mUserName;
    String                   mUserID;
    String                   mAgencyID;
    String                   mUserAccount;
    int                      mUserType;

    private CourseAdapter courseAdapter;
    private ExpiredCourseAdapter expiredCourseAdapter;
    IUserEnterPresenterImpl  mUserEnterPresenter;
    IUserPlayRecordPresenterImpl mUserPlayRecordPresenter;

    @BindView(R.id.tv_logout)
    TextView             mLogout;
    @BindView(R.id.tv_type)
    TextView           mSetType;
    @BindView(R.id.rl_type)
    RelativeLayout mRlType;
    @BindView(R.id.tv_status)
    TextView           mSetStatus;
    @BindView(R.id.rl_status)
    RelativeLayout mRlStatus;

    @BindView(R.id.lv_lesson)
    LoadMoreListView           mLvLesson;
    @BindView(R.id.rl_loading)
    RelativeLayout        mPbLoading;
//    @BindView(R.id.pb_loading)
//    ProgressBar        mPbLoading;
    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout mSwipeRefresh;
    @BindView(R.id.tv_no_data)
    TextView mTvNoData;

    private boolean isNoMoreData;
    private Handler mHandler=new Handler(){

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case GETCOURSESUC:
                    if (mPbLoading.getVisibility() == View.VISIBLE) {
                        mPbLoading.setVisibility(View.GONE);
                    }
                    if (mSwipeRefresh.isRefreshing()) {
                        mSwipeRefresh.setRefreshing(false);
                    }

                    expiredCourseAdapter = null;

                    if (courseAdapter == null) {
                        courseAdapter = new CourseAdapter(CourseInfoActivity.this, mCourseList);
                        mLvLesson.setAdapter(courseAdapter);
                    } else {
                        courseAdapter.notifyDataSetChanged();
                    }

                    mTvNoData.setVisibility(mCourseList.size() == 0 ? View.VISIBLE : View.GONE);

                    mLvLesson.setLoadingStatus(!isNoMoreData);

                    courseAdapter.setOnClick(new CourseAdapter.OnTestClick() {
                        @Override
                        public void OnClick(int i) {

                            if(!isEnterRoom){
                                isEnterRoom = !isEnterRoom;
                                mClickedRoomId = mCourseList.get(i).getRoomID();
                                mUserEnterPresenter.userEnterRoom(mCourseList.get(i).getRoomID(), mToken, mAgencyID);
                                FileLogUtils.write("EnterCourse: " + mCourseList.get(i).getRoomID() + "\t AgencyID:" + mAgencyID);
                            }

                        }
                    });

                    //进入第一个房间
                    if(!isEnterRoom){
                        isEnterRoom = !isEnterRoom;
                        mClickedRoomId = mCourseList.get(0).getRoomID();
                        mUserEnterPresenter.userEnterRoom(mCourseList.get(0).getRoomID(), mToken, mAgencyID);
                        FileLogUtils.write("EnterCourse: " + mCourseList.get(0).getRoomID() + "\t AgencyID:" + mAgencyID);
                    }


                    break;

                case GETCOURSEFAIL:
                    if (mPbLoading.getVisibility() == View.VISIBLE) {
                        mPbLoading.setVisibility(View.GONE);
                    }
                    if (mSwipeRefresh.isRefreshing()) {
                        mSwipeRefresh.setRefreshing(false);
                    }

                    int code = (int) msg.obj;
                    if (code == 0) {
                        Toast.makeText(CourseInfoActivity.this, getResources().getString(R.string.course_refresh), Toast.LENGTH_SHORT).show();
                    } else if (code == 1) {
                        Toast.makeText(CourseInfoActivity.this, getResources().getString(R.string.course_re_login), Toast.LENGTH_SHORT).show();
                    }
                    if (courseAdapter != null) {
                        courseAdapter.notifyDataSetChanged();
                    }
                    break;
                case GTEXPIREDCOURSESUC :
                    if (mPbLoading.getVisibility() == View.VISIBLE) {
                        mPbLoading.setVisibility(View.GONE);
                    }
                    if (mSwipeRefresh.isRefreshing()) {
                        mSwipeRefresh.setRefreshing(false);
                    }

                    courseAdapter = null;

                    if (expiredCourseAdapter == null) {
                        expiredCourseAdapter = new ExpiredCourseAdapter(CourseInfoActivity.this, mExpiredCourseList);
                        mLvLesson.setAdapter(expiredCourseAdapter);
                    } else {
                        expiredCourseAdapter.notifyDataSetChanged();
                    }

                    mTvNoData.setVisibility(mExpiredCourseList.size() == 0 ? View.VISIBLE : View.GONE);

                    mLvLesson.setLoadingStatus(!isNoMoreData);

                    expiredCourseAdapter.setOnClick(new ExpiredCourseAdapter.OnTestClick() {
                        @Override
                        public void OnClick(int i) {

                            if(!isEnterRoom){
                                isEnterRoom = !isEnterRoom;
                                mClickedRoomId = mExpiredCourseList.get(i).getRoomID();
                                mRecordName = mExpiredCourseList.get(i).getRoomTitle();
                                //mUserPlayRecordPresenter.userPlayRecord(mExpiredCourseList.get(i).getRoomID(), mAgencyID);
                                mUserPlayRecordPresenter.getRoomID(mClickedRoomId, mAgencyID);
                            }
                        }
                    });

                    break;
                case GTEXPIREDCOURSEFAL :
                    if (mPbLoading.getVisibility() == View.VISIBLE) {
                        mPbLoading.setVisibility(View.GONE);
                    }
                    if (mSwipeRefresh.isRefreshing()) {
                        mSwipeRefresh.setRefreshing(false);
                    }
                    if (expiredCourseAdapter != null) {
                        expiredCourseAdapter.notifyDataSetChanged();
                    }
                    break;
                default:
                    break;
            }
        }
    };
    private Dialog mTypeDialog;
    private Gson mGson;
    private double exitTime;
    public boolean isEnterRoom;
    private int mPage;
    private String mClickedRoomId;
    private String mRecordName;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //setContentView(R.layout.course_activity);


        setContentView(R.layout.activity_course);
        ButterKnife.bind(this);
        initData();

        mSwipeRefresh.setColorSchemeResources(android.R.color.holo_orange_light,
                                              android.R.color.holo_blue_bright,
                                              android.R.color.holo_green_light,
                                              android.R.color.holo_red_light);

        initListener();

        mUserEnterPresenter = new IUserEnterPresenterImpl(this, this);
        mUserPlayRecordPresenter = new IUserPlayRecordPresenterImpl(this, this);
    }

    private void initListener() {
        if (!mSwipeRefresh.isRefreshing()) {
            mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    FileLogUtils.write("Courses Refresh");

                    if (mCourseList != null) {
                        mCourseList.clear();
                    }
                    if (mExpiredCourseList != null) {
                        mExpiredCourseList.clear();
                    }
                    mPage = 1;
                    if (mT == 0) {
                        userGetCourse("", String.valueOf(mPage), String.valueOf(mS));
                    } else {
                        userGetCourse(String.valueOf(mT), String.valueOf(mPage), String.valueOf(mS));
                    }
                }
            });
        }

        mLvLesson.setOnLoadMoreListener(new LoadMoreListView.OnLoadMoreListener() {
            @Override
            public void onLoadingMore() {
                //上拉加载更多数据
                FileLogUtils.write("Courses LoadMore");
                mLvLesson.setLoadingStatus(false);

                mPage++;
                if (mT == 0) {
                    userGetCourse("", String.valueOf(mPage), String.valueOf(mS));
                } else {
                    userGetCourse(String.valueOf(mT), String.valueOf(mPage), String.valueOf(mS));
                }
            }
        });
    }

    private void userGetCourse(String roomType, String page, String expires) {
        //这里进行网络请求登录
        /**
         *
         Version：字符串，接口的版本号，与本文档版本一致。
         UA：字符串，客户端类型。iOS/Android/Windows/MacOS。
         UserAccount：字符串，机构用户账号。
         UserID：字符串，机构用户 ID。
         UserType：数值，用户类型。1 老师，2 学生，3 助教，4
         巡视员。
         Token：字符串，从 agent_user_login 接口获得。
         VerificationKey：密文。机构+时间字符串
         *
         */

        VerificationKeyUtils keyUtils = new VerificationKeyUtils();
        String VerificationKey = keyUtils.getVerificationKey(mAgencyID);
        //LogUtil.i("MVP","获取课表    MECHANISM_ID --> "+mAgencyID);
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("UA", "Android");
        params.addBodyParameter("Version", Info.APIVERSION);
        params.addBodyParameter("UserAccount",mUserAccount );
        params.addBodyParameter("UserType", mUserType+"");
        params.addBodyParameter("UserID", mUserID);
        params.addBodyParameter("Token", mToken);
        params.addBodyParameter("VerificationKey", VerificationKey);
        params.addBodyParameter("RoomType", roomType);
        params.addBodyParameter("Page", page);
        params.addBodyParameter("Expires", expires);

        FileLogUtils.write("Get Course: " + Constant.getCourseList());
        //LogUtil.i("MVP","获取课表    VerificationKey --> "+VerificationKey);
        httpUtils.send(HttpRequest.HttpMethod.POST, Constant.getCourseList(), params, new RequestCallBack<String>() {
        //httpUtils.send(HttpRequest.HttpMethod.POST, "http://118.31.64.8/live/agent_user_get_room", params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                LogUtil.i("MVP", "课表 response "+responseInfo.result);
                //Logger.json(responseInfo.result);
                if (mGson == null) {
                    mGson = new Gson();
                }

                try {
                    JSONObject responJson = new JSONObject(responseInfo.result);

                    if (responJson.getBoolean("Result")) {
                        if(responJson.has("Rooms")){
                            JSONArray rooms = responJson.getJSONArray("Rooms");

                            if (mCourseList == null) {
                                mCourseList = new ArrayList<>();
                            }

                            if (mS == 0) {
                                if (rooms.length() == 0) {
                                    isNoMoreData = true;
                                } else {
                                    isNoMoreData = false;

                                    for (int i = 0; i < rooms.length(); i++) {

                                        JSONObject jsonObject = rooms.optJSONObject(i);

                                        RoomsBean roomsBean = mGson.fromJson(jsonObject.toString(), RoomsBean.class);

                                        mCourseList.add(roomsBean);
                                    }
                                }

                                Message msg = Message.obtain();
                                msg.what=GETCOURSESUC;
                                mHandler.sendMessage(msg);
                            }
                        }

                        if(responJson.has("ExpiredRooms")){
                            JSONArray expiredRooms = responJson.getJSONArray("ExpiredRooms");

                            if (mExpiredCourseList == null) {
                                mExpiredCourseList = new ArrayList<>();
                            }

                            if (mS == 1) {
                                if (expiredRooms.length() == 0) {
                                    isNoMoreData = true;
                                } else {
                                    isNoMoreData = false;

                                    for (int i=0;i<expiredRooms.length();i++){
                                        JSONObject jsonObject = expiredRooms.optJSONObject(i);
                                        ExpiredRoomsBean expiredRoomsBean = mGson.fromJson(jsonObject.toString(), ExpiredRoomsBean.class);
                                        mExpiredCourseList.add(expiredRoomsBean);
                                    }
                                }

                                Message msg = Message.obtain();
                                msg.what=GTEXPIREDCOURSESUC;
                                mHandler.sendMessage(msg);
                            }

                        }
                    } else {
                        Message msg = Message.obtain();
                        msg.obj = 1;
                        msg.what=GETCOURSEFAIL;
                        mHandler.sendMessage(msg);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    Message msg = Message.obtain();
                    msg.obj = 0;
                    msg.what=GETCOURSEFAIL;
                    mHandler.sendMessage(msg);
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Message msg = Message.obtain();
                msg.obj = 0;
                msg.what=GETCOURSEFAIL;
                mHandler.sendMessage(msg);
            }
        });

    }

    private void initData() {

        Intent intent = getIntent();
        if (intent != null) {

            mToken = intent.getStringExtra("token");
            mUserName = intent.getStringExtra("UserName");
            mUserID = intent.getStringExtra("UserID");
            mUserAccount= intent.getStringExtra("UserAccount");
            mAgencyID = intent.getStringExtra("AgencyID");
            mUserType = intent.getIntExtra("UserType", 0);

        }

        mType = getString(R.string.course_course_all);
        mStatus = getString(R.string.course_status_incompleted);

        mSetType.setText(mType);
        mSetStatus.setText(mStatus);

        mPbLoading.setVisibility(View.VISIBLE);
        mPage = 1;
        userGetCourse("", String.valueOf(mPage), "0");
    }

    @OnClick({R.id.tv_logout, R.id.rl_type, R.id.rl_status})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_logout:
                new AlertDialog.Builder(CourseInfoActivity.this).setTitle(getResources().getString(R.string.course_tip))
                        .setMessage(getResources().getString(R.string.course_whether_sign_out))
                        .setIcon(android.R.drawable.ic_dialog_info)
                        .setPositiveButton(getResources().getString(R.string.course_sure), new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 点击“确认”后的操作
                                ((TalkApplication) getApplication()).isAutoLogin(false);
                                SharedPreferences sp = getSharedPreferences(USER_PWD, Context.MODE_PRIVATE);

                                SharedPreferences.Editor editor = sp.edit();
                                editor.clear();
                                editor.commit();
                                Intent intent = new Intent(CourseInfoActivity.this, LoginActivity.class);
                                startActivity(intent);
                                CourseInfoActivity.this.finish();
                            }
                        })
                        .setNegativeButton(getResources().getString(R.string.course_cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 点击“返回”后的操作,这里不设置没有任何操作
                                dialog.dismiss();
                            }
                        }).show();
                break;

            case R.id.rl_type:
                shogDialogTypeSelest("type");
                break;

            case R.id.rl_status:
                shogDialogTypeSelest("status");
                break;
        }
    }


    private void shogDialogTypeSelest(final String dialogType) {
        String[] data = {};
        if (dialogType.equals("type")) {
            data = getResources().getStringArray(R.array.eclass_type);
        } else if (dialogType.equals("status")) {
            data = getResources().getStringArray(R.array.eclass_status);
        }

        View view = View.inflate(CourseInfoActivity.this, R.layout.dialog_course_type, null);
        mTypeDialog = new Dialog(CourseInfoActivity.this, R.style.courseTypeDialogStyle);
        mTypeDialog.setContentView(view);

        mTypeDialog.show();
        mTypeDialog.setCancelable(true);
        mTypeDialog.setCanceledOnTouchOutside(true);

        WindowManager windowManager = (WindowManager)getSystemService(Context.WINDOW_SERVICE);

        int screenWidth = windowManager.getDefaultDisplay().getWidth();

        WindowManager.LayoutParams params = mTypeDialog.getWindow().getAttributes();
        params.width = screenWidth * 5 / 9;
        mTypeDialog.getWindow().setAttributes(params);

        ListView lvType = (ListView) view.findViewById(R.id.lv_type);
        lvType.setAdapter(new TypeListAdapter(data));
        final String[] finalDala = data;
        lvType.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mTypeDialog.dismiss();
                if (dialogType.equals("type")) {
                    //mType = mCourseType[position];
                    mType = finalDala[position];
                    mSetType.setText(mType);
                    if (mType.equals(getString(R.string.course_course_all))) {
                        mT = 0;
                    } else if (mType.equals(getString(R.string.course_1_V_1_class))) {
                        mT = 1;
                    } else if (mType.equals(getString(R.string.course_small_class))) {
                        mT = 2;
                    } else if(mType.equals(getString(R.string.course_large_class))){
                        mT = 3;
                    }
                } else if (dialogType.equals("status")) {
                    mStatus = finalDala[position];
                    mSetStatus.setText(mStatus);
                    if (mStatus.equals(getResources().getString(R.string.course_status_incompleted))) {
                        mS = 0;
                    } else {//已结束
                        mS = 1;
                    }
                }

                showLessonView(mT, mS);
            }
        });
    }

    private void showLessonView(int type, int status) {
        mPage = 1;
        if (mCourseList != null) {
            mCourseList.clear();
        }
        if (mExpiredCourseList != null) {
            mExpiredCourseList.clear();
        }
        if (type == 0) {
            userGetCourse("", String.valueOf(mPage), String.valueOf(status));
        } else {
            userGetCourse(String.valueOf(type), String.valueOf(mPage), String.valueOf(status));
        }
    }

    @Override
    public void showProgress() {
        ThreadUtils.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                mPbLoading.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void hideProgress() {
        ThreadUtils.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                mPbLoading.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void getCourseLists(ArrayList<RoomsBean> roomsBeanArrayList, ArrayList<ExpiredRoomsBean> expiredRoomsBeanArrayList) {

    }

    @Override
    public void showErrorCode(final int type, final String str) {
        ThreadUtils.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                //ToastUtils.showToast(CourseInfoActivity.this, str);
                mPbLoading.setVisibility(View.GONE);
                isEnterRoom = false;

                if (type == 0) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(CourseInfoActivity.this)
                            .setTitle(getResources().getString(R.string.course_tip))
                            .setMessage(str)
                            .setIcon(android.R.drawable.ic_dialog_info)
                            .setPositiveButton(getResources().getString(R.string.course_enter_course_failed_setting), new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                /*Intent intent = new Intent(Intent.ACTION_MAIN);
                                intent.setClassName("com.android.phone", "com.android.phone.NetworkSetting");
                                startActivity(intent);*/
                                /*Intent intent=new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
                                ComponentName cName = new ComponentName("com.android.phone", "com.android.phone.Settings");
                                intent.setComponent(cName);*/
                                /*Intent intent = new Intent("android.settings.WIFI_SETTINGS");
                                startActivity(intent);*/
                                    //Intent intent = new Intent("android.settings.WIRELESS_SETTINGS");
                                    Intent intent = new Intent(Settings.ACTION_SETTINGS);
                                    startActivity(intent);
                                }
                            })
                            .setNegativeButton(getResources().getString(R.string.course_enter_course_failed_try), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (mS == 0) {
                                        mUserEnterPresenter.userEnterRoom(mClickedRoomId, mToken,mAgencyID);
                                    } else if (mS == 1) {
                                        mUserPlayRecordPresenter.userPlayRecord(mClickedRoomId, mAgencyID);
                                    }
                                    dialog.dismiss();
                                    mPbLoading.setVisibility(View.VISIBLE);
                                }
                            });
                    AlertDialog alertDialog = builder.show();
                    alertDialog.setCancelable(true);
                    alertDialog.setCanceledOnTouchOutside(true);
                } else if (type == 1) {
                    Toast.makeText(CourseInfoActivity.this, str, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void playRecordSuc(String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        startActivity(intent);
    }

    @Override
    public void playRecordFal() {
        ThreadUtils.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showToast(CourseInfoActivity.this, getResources().getString(R.string.open_record_fail));
            }
        });
    }

    @Override
    public void getRoomIDSuccess(String roomID) {
        RecordPlayerActivity.JumpInto(this, roomID, mRecordName);
    }

    @Override
    public void getRoomIDFailure(String error) {
        ToastUtils.showToast(CourseInfoActivity.this, error);
    }

    class TypeListAdapter extends BaseAdapter {

        String[] strs;

        public TypeListAdapter(String[] strs) {
            this.strs = strs;
        }

        @Override
        public int getCount() {
            return strs != null ? strs.length : 0;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(CourseInfoActivity.this,
                                           R.layout.item_course_type,
                                           null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.tvType.setText(strs[position]);
            return convertView;
        }
    }

    class ViewHolder{
        TextView tvType;
        public ViewHolder(View root){
            tvType = (TextView) root.findViewById(R.id.tv_course_type);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            if ((System.currentTimeMillis() - exitTime) > 3000) {
                Toast.makeText(getApplicationContext(), getResources().getString(R.string.course_exit_app), Toast.LENGTH_SHORT)
                     .show();
                exitTime = System.currentTimeMillis();
            } else {
                return super.onKeyDown(keyCode, event);
            }
        }

        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        isEnterRoom = false;
    }
}




